<?php
class topic_db{
	var $sql;
	var $table = "jishigou_topic";
	var $table_to;
	var $lageid=10;
	var $mysql;

	function topic_db($mysql,$sql){
		$this->sql=$sql;
		$this->mysql=$mysql;
		$this->judge_sql();

	}


	function judge_sql(){
		$sql = trim($this->sql);

		if (preg_match ("/^\b(select)\b.*?\b(from)\b.*?(jishigou_topic).*?\b(where)\b/is", $sql)){
			$this->sql = $this->select_sql($sql);
		}
		if (preg_match ("/^\b(insert)\b.*?(jishigou_topic).*?\b(values)\b.*?/is", $sql)){
			$this->sql = $this->insert_sql($sql);
		}
		if (preg_match ("/^\b(update)\b.*?(jishigou_topic).*?\b(set)\b.*?\bwhere\b/is", $sql)){
			$this->sql = $this->update_sql($sql);
		}
		if (preg_match ("/^\b(delete)\b.*?jishigou_topic.*?\bwhere\b.*?/is", $sql)){
			$this->sql = $this->delete_sql($sql);
		}

	}

	function delete_sql($sql){
		if ($c=preg_match_all ("/^\bdelete\s{0,}from\b.*?jishigou_topic.*?\bwhere\b(.*?)$/is", $sql, $matches)){
			$delete="delete from ";
			$where=$matches[1][0];
			if(preg_match("/.*?\b(tid)\b.*?/is", $where)){
				$tablename=$this->by_tids($where);
			}
			foreach($tablename as $v){
				$change_sql=$change_sql.$delete.$v." where ".$where." ;";
			}
			return $change_sql;
		}

		print_r("topic.db.php::".$sql);exit;
	}
	function update_sql($sql){
		if ($c=preg_match_all ("/^\bupdate\b.*?jishigou_topic.*?\bset\b(.*?)\bwhere\b(.*?)$/is", $sql, $matches)){

			$update="UPDATE ";
			$sets=$matches[1][0];
			$where=$matches[2][0];
			if(preg_match("/.*?\b(tid)\b.*?/is", $where)){
				$tablename=$this->by_tids($where);
			}
			foreach($tablename as $v){
				$up_sql=$update.$v." set ".$sets." where ".$where." ;";
                $q =$this->mysql->Query($up_sql);
			}
			return "select * from jishigou_tables where day ='201106'";
		}
		print_r("topic.db.php::".$sql);exit;
	}

	function insert_sql($sql){

		$this->creat_table();
		$_tabls="UPDATE ".TABLE_PREFIX."tables SET tid =tid+1 where tablename='$this->table' and day='".date("Ym")."'";
		$q =$this->mysql->Query($_tabls);

		if ($c=preg_match_all ("/^\binsert\s{0,}into\b.*?\bjishigou_topic\b`{0,}(.*?)$/is", $sql, $matches)){
			$insert="insert into ";
			$values=$matches[1][0];
			$tablename=$this->table.date("Ym");
			return $insert.$tablename." ".$values;
		}
		print_r("topic.db.php::".$sql);exit;
	}

	function select_sql($sql){
//		print_r($sql);echo "<br/>";
		$this->creat_table();

		if ($c=preg_match_all ("/(.*?)\b(from)\b(.*?)\b(where)\b(.*?)$/is", $sql, $matches)){
			$selsect=$matches[1][0];
			$from = $matches[3][0];
			$where=$matches[5][0];
			//print_r($where);echo "<br/>";
			if	(preg_match("/.*?\b(tid)\b.*?in.*?/is", $where)){
				$c_table = $this->select_tid($selsect,$where);
			}elseif(preg_match("/.*?\b(tid)\b.*?=.*?/is", $where)){
				$c_table = $this->select_tid($selsect,$where);
			}elseif(preg_match("/.*?\b(limit)\b\s{0,}.*?/is", $where)){
				$c_table = $this->select_limit($selsect,$where);
			}elseif (preg_match("/.*?\b(dateline)\b.*?/is", $where)){
				$c_table = $this->select_by_dateline($selsect,$where);
			}elseif (preg_match("/.*?\b(count)\b.*?/is", $selsect)){
				$c_table = $this->_count($selsect,$where);
			}else{
				$c_table = $this->select_all_table($selsect,$where);
			}
			//$change_sql=$selsect." from (".$c_table.") as tab where ".$where;
			//print_r($c_table);echo "<br/>";
			return $c_table;
		}
		print_r("topic.db.php::".$sql);exit;
	}
	function _count($selsect,$where){
		$c_table = $this->select_all_table($selsect,$where);
		return "SELECT sum(total_record) AS total_record FROM (".$c_table.") as tab";
	}

	function select_tid($selsect,$where){
		$tablename=$this->by_tids($where);
		foreach($tablename as $v){
			$table[]="(".$selsect." from ".$v ." where ".$where.")";
		}

		return implode(" union all ",$table);
	}
	function by_tids($where){
//				print_r($where);echo '<br/>';
		if($c=preg_match_all ("/.*?\btid\b.*?in\s?\((.*?)\).*?$/is", $where, $matches)){
			$tids=$matches[1][0];
			$tids=split(",",$tids);
			foreach($tids as $v){
				if($c=preg_match_all ("/[?:\"|\']?(.*?)[?:\"|\']?$/is", $v, $matches)){
					$tid[]=$matches[1][0];
				}
			}
			asort($tid);
			$tid = array_values($tid);
			$_tabls="select * from ".TABLE_PREFIX."tables where tablename='$this->table' and tid >= $tid[0] order by tid";
			$_info = $this->mysql->Query($_tabls);
			while ($row = $_info->GetRow()){
				$tablename[]=$row[tablename].$row[day];
				if($row[tid] > end($tid)){
					break;
				}
			}
		}elseif($c=preg_match_all ("/.*?tid.*?=\s?[?:\"|\']?(\d{0,})[?:\"|\']?.*?$/is", $where, $matches)){
			$tid=$matches[1][0];
			$_tabls="select * from ".TABLE_PREFIX."tables where tablename='$this->table' and fid<=$tid and tid>=$tid";
//			print_r($_tabls);
			$_info = $this->mysql->FetchFirst($_tabls);
			$tablename[]= $_info[tablename].$_info[day];
		}
		return $tablename;
	}


	function select_limit($selsect,$where){
		//print_r($selsect);echo "<br/>";
		if($c=preg_match_all ("/.*?\bLIMIT\b\s{0,}(\d{0,}),?(\d{0,})/is", $where, $matches)){
			$start=$matches[1][0];
			$end=$matches[2][0];
			if(empty($end)){
				$end = $start;
				$start =0 ;
			}
			$_tabls="select * from ".TABLE_PREFIX."tables where tablename='$this->table' order by day desc";
			$_info = $this->mysql->Query($_tabls);
			while ($row = $_info->GetRow()){
				$tablename[]=$row[tablename].$row[day];
			}
			$count=0;
			foreach($tablename as $v){
				$_tabls=$selsect." from ".$v." where ".$where;
				$query=$this->mysql->Query($_tabls);
				$_info = $query->GetNumRows($_tabls);
				$count=$count+intval($_info);
				$tb[]=$v;
				if($count >= ($end)){
					break;
				}
			}
			if(isset($tb)){
				foreach($tb as $v){
					$table[]="(".$selsect." from ".$v ." where ".$where.")";
				}
			}
			if(empty($table)){
				$table[] = "(".$selsect." from ".$this->table.date("Ym")." where ".$where.")";
			}

			return implode(" union all ",$table);
		}
	}
	function select_by_dateline($select,$where){
	 //print_r($select);echo"<br/>";
		if ($c=preg_match_all ("/.*?(dateline)`?\s{0,}([>]{0,}[>=]{0,}[<]{0,}[<=]{0,})\s{0,}'?(\d{5,})/is", $where, $matches)){
			$day=date('Ym',$matches[3][0]);
			$bxd=$matches[2][0];
			if($bxd =='<'){
				$_tabls="select * from ".TABLE_PREFIX."tables where tablename='$this->table' and day <='$day' ";
			}else{
				$_tabls="select * from ".TABLE_PREFIX."tables where tablename='$this->table' and day >='$day' order by day desc";
			}
			$_info = $this->mysql->Query($_tabls);

			while ($row = $_info->GetRow()){
				$tablename[]="(".$select." from ".$row[tablename].$row[day]." where ".$where." )";
			}

			return implode(" union all ",$tablename);
		}


	}



	function select_all_table($selsect,$where){
		$_tabls="select * from ".TABLE_PREFIX."tables where tablename='$this->table'";
		$_info = $this->mysql->Query($_tabls);
		while ($row = $_info->GetRow()){
			$tablename[]="(".$selsect." from ".$row[tablename].$row[day]." where ".$where.")";
		}
		return implode(" union all ",$tablename);
	}


	function creat_table(){
		$last_day = strtotime("-1 month", time());
		$_tabls="select * from ".TABLE_PREFIX."tables where tablename='$this->table' and day='".date("Ym")."'";
		$_info = $this->mysql->FetchFirst($_tabls);
		if(empty($_info)){
			$_tabls="select * from ".TABLE_PREFIX."tables where day='".date("Ym", $last_day)."' and tablename='".$this->table."'";
			$_info = $this->mysql->FetchFirst($_tabls);
			if(empty($_info)){
				$_tabls="INSERT INTO ".TABLE_PREFIX."tables (fid,tid,tablename,day) VALUES (0,0,'$this->table','".date('Ym')."')" ;
				$_info = $this->mysql->Query($_tabls);
				$_tabls="CREATE TABLE IF NOT EXISTS `".$this->table.date('Ym')."` (
                `tid` int(10) unsigned NOT NULL auto_increment,
                `uid` mediumint(8) unsigned NOT NULL default '0',
                `username` char(15) NOT NULL default '',
                `content` char(255) NOT NULL default '',
                `content2` char(255) NOT NULL default '',
                `imageid` int(10) unsigned NOT NULL default '0',
                `videoid` int(10) unsigned NOT NULL default '0',
                `musicid` int(10) unsigned NOT NULL default '0',
                `roottid` int(10) unsigned NOT NULL default '0',
                `replys` smallint(4) unsigned NOT NULL default '0',
                `forwards` smallint(6) NOT NULL default '0',
                `totid` int(10) unsigned NOT NULL default '0',
                `touid` mediumint(8) unsigned NOT NULL default '0',
                `tousername` char(15) NOT NULL default '',
                `dateline` int(10) unsigned NOT NULL default '0',
                `lastupdate` int(10) unsigned NOT NULL default '0',
                `from` enum('web','wap','mobile','qq','msn','api','sina','qqwb','vote') NOT NULL default 'web',
                `type` enum('first','forward','reply','both') NOT NULL default 'first',
                `item_id` int(10) unsigned NOT NULL default '0',
                `item` char(15) NOT NULL default '',
                PRIMARY KEY  (`tid`),
                KEY `uid_type` (`uid`,`type`),
                KEY `dateline` (`dateline`),
                KEY `item_id_item` (`item_id`,`item`)
                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT= 0;";
				$q =$this->mysql->Query($_tabls);
			}else{
				$_tabls="SHOW TABLE STATUS LIKE '".$this->table.date("Ym", $last_day)."'";
				$q =$this->mysql->Query($_tabls);
				$values=$q->GetRow("both");
				$auto_increment = $values['Auto_increment'];
				$_tabls="CREATE TABLE IF NOT EXISTS `".$this->table.date('Ym')."` (
				`tid` int(10) unsigned NOT NULL auto_increment,
				`uid` mediumint(8) unsigned NOT NULL default '0',
				`username` char(15) NOT NULL default '',
				`content` char(255) NOT NULL default '',
				`content2` char(255) NOT NULL default '',
				`imageid` int(10) unsigned NOT NULL default '0',
				`videoid` int(10) unsigned NOT NULL default '0',
				`musicid` int(10) unsigned NOT NULL default '0',
				`roottid` int(10) unsigned NOT NULL default '0',
				`replys` smallint(4) unsigned NOT NULL default '0',
				`forwards` smallint(6) NOT NULL default '0',
				`totid` int(10) unsigned NOT NULL default '0',
				`touid` mediumint(8) unsigned NOT NULL default '0',
				`tousername` char(15) NOT NULL default '',
				`dateline` int(10) unsigned NOT NULL default '0',
				`lastupdate` int(10) unsigned NOT NULL default '0',
				`from` enum('web','wap','mobile','qq','msn','api','sina','qqwb','vote') NOT NULL default 'web',
				`type` enum('first','forward','reply','both') NOT NULL default 'first',
				`item_id` int(10) unsigned NOT NULL default '0',
				`item` char(15) NOT NULL default '',
				PRIMARY KEY  (`tid`),
				KEY `uid_type` (`uid`,`type`),
				KEY `dateline` (`dateline`),
				KEY `item_id_item` (`item_id`,`item`)
				) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT= $auto_increment;";
				$q =$this->mysql->Query($_tabls);


				$_tabls="UPDATE ".TABLE_PREFIX."tables set tid=".($auto_increment-1)." where tablename = '".$this->table."' and day = '".date('Ym',$last_day)."'" ;
				$q =$this->mysql->Query($_tabls);
				$_tabls="INSERT INTO ".TABLE_PREFIX."tables (fid,tid,tablename,day) VALUES ($auto_increment,$auto_increment,'$this->table','".date('Ym')."')" ;
				$_info = $this->mysql->Query($_tabls);
					
			}

		}
	}
}
?>